package com.fary.service;

import com.fary.loadbalance.LoadBalancer;
import com.fary.openfeign.ProducerServiceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

@RestController
public class OrderService {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;
    @Autowired
    private LoadBalancer loadBalancer;

    @RequestMapping("/orderToMember")
    public String orderToMember() {
        // 从注册中心上获取该注册服务列表
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances("nacos-producer");
        ServiceInstance serviceInstance = loadBalancer.getSingleAddress(serviceInstanceList);
        URI rpcMemberUrl = serviceInstance.getUri();
        // 使用本地rest形式实现rpc调用
        String result = restTemplate.getForObject(rpcMemberUrl + "/getUser?userId=1", String.class);
        return "订单调用会员获取结果:" + result;
    }

    @Autowired
    private ProducerServiceFeign producerServiceFeign;

    /**
     * 基于我们的feign客户端形式实现rpc远程调用
     */
    @RequestMapping("/orderFeignToMember")
    public String orderFeignToMember() {
        String result = producerServiceFeign.getUser(1);
        return "我是订单服务调用会员服务的接口,返回结果" + result;
    }
}